<template>
  <div class="room-add">
    <h2 class="title">添加房源</h2>
    <form class="form" @submit.prevent="handleSubmit">
      <div class="form-row">
        <label>房源标题</label>
        <input v-model.trim="form.houseTitle" type="text" placeholder="请输入房源标题" required />
      </div>

      <div class="form-row">
        <label>地址</label>
        <input v-model.trim="form.address" type="text" placeholder="请输入地址" required />
      </div>

      <div class="form-row two">
        <div class="col">
          <label>面积(㎡)</label>
          <input v-model.number="form.rentArea" type="number" min="0" step="1" placeholder="例如 68" required />
        </div>
        <div class="col">
          <label>租金(挂牌)</label>
          <input v-model.number="form.rentPriceListing" type="number" min="0" step="1" placeholder="例如 3200" required />
        </div>
      </div>

      <div class="form-row">
        <label>租金单位</label>
        <select v-model="form.rentPriceUnit" required>
          <option value="月付">月付</option>
          <option value="季付">季付</option>
          <option value="年付">年付</option>
        </select>
      </div>

      <div class="form-row">
        <label>距离信息</label>
        <input v-model.trim="form.distanceInfo" type="text" placeholder="如 距离地铁300米" />
      </div>

      <div class="form-row">
        <label>省份ID</label>
        <input v-model.number="form.provinceld" type="number" min="0" step="1" placeholder="如 56000" required />
      </div>

      <div class="form-row">
        <label>房源描述</label>
        <textarea v-model.trim="form.description" rows="4" placeholder="请输入房源描述"></textarea>
      </div>

      <div class="form-row">
        <label>封面图片</label>
        <div class="upload">
          <input ref="fileInput" type="file" accept="image/*" @change="onFileChange" />
          <button type="button" class="btn" @click="triggerSelect">选择图片</button>
          <span class="tip" v-if="fileName">已选择：{{ fileName }}</span>
          <img v-if="previewUrl" :src="previewUrl" class="preview" alt="预览" />
          <button type="button" class="btn" :disabled="uploading || !selectedFile" @click="uploadImage">
            {{ uploading ? '上传中...' : '上传到云端' }}
          </button>
          <span class="tip success" v-if="form.housePicture">已上传：{{ form.housePicture }}</span>
        </div>
      </div>

      <div class="actions">
        <button class="btn primary" type="submit" :disabled="submitting">{{ submitting ? '提交中...' : '提交' }}</button>
        <button class="btn" type="button" @click="resetForm" :disabled="submitting || uploading">重置</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { addHouseApi } from '@/api/room'
import { uploadFile } from '@/api/auth'

const form = reactive({
  houseTitle: '',
  address: '',
  rentArea: null,
  rentPriceListing: null,
  rentPriceUnit: '月付',
  housePicture: '',
  description: '',
  distanceInfo: '',
  provinceld: null
})

const submitting = ref(false)
const uploading = ref(false)
const selectedFile = ref(null)
const fileInput = ref(null)
const previewUrl = ref('')
const fileName = computed(() => selectedFile.value?.name || '')

const triggerSelect = () => fileInput.value && fileInput.value.click()

const onFileChange = (e) => {
  const file = e.target.files && e.target.files[0]
  if (!file) return
  selectedFile.value = file
  const reader = new FileReader()
  reader.onload = (ev) => {
    previewUrl.value = ev.target.result
  }
  reader.readAsDataURL(file)
}

const uploadImage = async () => {
  if (!selectedFile.value) return
  uploading.value = true
  try {
    const url = await uploadFile(selectedFile.value)
    form.housePicture = url
    ElMessage.success('图片上传成功')
  } catch (e) {
    ElMessage.error(e.message || '图片上传失败')
  } finally {
    uploading.value = false
  }
}

const validate = () => {
  if (!form.houseTitle) return '请填写房源标题'
  if (!form.address) return '请填写地址'
  if (form.rentArea == null || form.rentArea < 0) return '请填写有效的面积'
  if (form.rentPriceListing == null || form.rentPriceListing < 0) return '请填写有效的租金'
  if (!form.rentPriceUnit) return '请选择租金单位'
  if (!form.housePicture) return '请先上传封面图片'
  if (form.provinceld == null) return '请填写省份ID'
  return ''
}

const handleSubmit = async () => {
  const err = validate()
  if (err) {
    ElMessage.warning(err)
    return
  }
  submitting.value = true
  try {
    await addHouseApi({ ...form })
    ElMessage.success('添加成功')
    resetForm()
  } catch (e) {
    ElMessage.error(e.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  form.houseTitle = ''
  form.address = ''
  form.rentArea = null
  form.rentPriceListing = null
  form.rentPriceUnit = '月付'
  form.housePicture = ''
  form.description = ''
  form.distanceInfo = ''
  form.provinceld = null
  selectedFile.value = null
  previewUrl.value = ''
  if (fileInput.value) fileInput.value.value = ''
}
</script>

<style scoped>
.room-add {
  padding: 16px;
}
.title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
}
.form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.form-row {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.form-row.two {
  flex-direction: row;
  gap: 12px;
}
.form-row.two .col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}
label { font-size: 14px; color: #333; }
input, select, textarea {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 10px 12px;
  font-size: 14px;
  outline: none;
}
.upload { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.preview { width: 120px; height: 80px; object-fit: cover; border-radius: 6px; border: 1px solid #eee; }
.tip { font-size: 12px; color: #666; }
.tip.success { color: #16a34a; }
.actions { display: flex; gap: 10px; margin-top: 8px; }
.btn {
  border: 1px solid #e5e7eb;
  background: #fff;
  padding: 8px 12px;
  border-radius: 8px;
  cursor: pointer;
}
.btn.primary { background: #6366f1; color: #fff; border-color: #6366f1; }
</style>

